package com.netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

public class NettyHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		System.out.println("Server： " + ctx.channel().remoteAddress() + "已连接！");
	}
	
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		System.out.println("Server： " + ctx.channel().remoteAddress() + "断开连接！");
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {
			ByteBuf buf = (ByteBuf) msg;
			byte[] bytes = new byte[buf.readableBytes()];
			buf.readBytes(bytes);
			ctx.channel().writeAndFlush("来自服务器的消息!!".getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			ReferenceCountUtil.release(msg);
		}
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println("Server： Exception  " + ctx.channel().remoteAddress() + cause.getMessage());
	}
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		IdleState state = ((IdleStateEvent) evt).state();
		if(state == IdleState.READER_IDLE){
			System.out.println(state);
		}
		if(state == IdleState.WRITER_IDLE){
			System.out.println(state);
		}
		if(state == IdleState.ALL_IDLE){
			System.out.println(state);
		}
//		ctx.close();
	}
	
}
